package com.study.traincard;

import com.study.traincard.database.Form;
import com.study.traincard.database.FormDatabase;
import com.study.traincard.slice.MainAbilitySlice;
import com.study.traincard.widget.controller.*;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.ComponentProvider;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.data.preferences.Preferences;
import ohos.global.icu.text.SimpleDateFormat;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;


import java.text.ParseException;
import java.util.Date;
import java.util.List;

public class MainAbility extends Ability {
    private static final int INVALID_FORM_ID = -1;
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, MainAbility.class.getName());
    private String topWidgetSlice;
    private Date df;

    private final DatabaseHelper helper = new DatabaseHelper(this);
    private OrmContext connect;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        connect = helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class);
        // 启动TimerAbility
        Intent intentService = new Intent();
        Operation operation =
                new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName(TimerAbility.class.getName())
                        .build();
        intentService.setOperation(operation);
        startAbility(intentService);

    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        HiLog.info(TAG, "onCreateForm");
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, 3);
        HiLog.info(TAG, "onCreateForm: formId=" + formId + ",formName=" + formName);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController = (formController == null) ? formControllerManager.createFormController(formId,
                formName, dimension) : formController;
        if (formController == null) {
            HiLog.error(TAG, "Get null controller. formId: " + formId + ", formName: " + formName);
            return null;
        }
        ProviderFormInfo providerFormInfo = formController.bindFormData(formId);
//               return formController.bindFormData(formId);
        Context context = getContext();
        //创建数据库
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        String filename = "traindb";
        Preferences preferences = databaseHelper.getPreferences(filename);

        //读数据库信息，并展示
        String str_trainstart = preferences.getString("trainstart", "");
        String str_trainstart_time = preferences.getString("trainstart_time", "");
        String str_trainend = preferences.getString("trainend", "");
        String str_trainend_time = preferences.getString("trainend_time", "");
        String str_trainserial = preferences.getString("trainserial", "");
        String str_seatingno = preferences.getString("seatingno", "");
        String str_traveller_name = preferences.getString("traveller_name", "");
        String str_journey_date = preferences.getString("journey_date", "");
        String str_checkport=preferences.getString("check_port","");
        String str_trainclass=preferences.getString("trainclass","");


        //合成当前旅行日期
        String journeyDate = str_journey_date + str_trainstart_time;
        if (!journeyDate.isEmpty()) {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
            try {
                df = sd.parse(journeyDate);

            } catch (ParseException e) {
                e.printStackTrace();
            }
            // 存储卡片信息
            Form form = new Form(formId, formName, dimension, df, str_trainstart, str_trainstart_time,
                    str_trainend,str_trainend_time, str_trainserial, str_seatingno, str_traveller_name,
                    str_journey_date,str_checkport,str_trainclass,true);
            if(connect==null){
                connect =
                        helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class);
            }
            connect.insert(form);
        } else {
            // 存储卡片信息
            Form form = new Form(formId, formName, dimension,false);
            if (connect == null) {
                connect =
                        helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class);
            }
            connect.insert(form);
        }
        connect.flush();

        if (dimension == 3) {
            ComponentProvider componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_info_widget_2_4, this);
            if (!str_trainstart.isEmpty()) {
                componentProvider.setText(ResourceTable.Id_s1_trainstart, str_trainstart);
                componentProvider.setText(ResourceTable.Id_s1_trainstart_time, str_trainstart_time);
                componentProvider.setText(ResourceTable.Id_s1_trainend, str_trainend);
                componentProvider.setText(ResourceTable.Id_s1_trainend_time, str_trainend_time);
                componentProvider.setText(ResourceTable.Id_s1_trainserial, str_trainserial);
                componentProvider.setText(ResourceTable.Id_s1_seatingno, str_seatingno);
                componentProvider.setText(ResourceTable.Id_s1_travellername, str_traveller_name);
                componentProvider.setText(ResourceTable.Id_s1_journy_date, str_journey_date);
                componentProvider.setText(ResourceTable.Id_s1_check_port, str_checkport);
            }
            providerFormInfo.mergeActions(componentProvider);
        }
        if (dimension == 2) {
            ComponentProvider componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_info_widget_2_2, this);
            if (!str_trainstart.isEmpty()) {
                componentProvider.setText(ResourceTable.Id_s2_trainstart, str_trainstart);
                componentProvider.setText(ResourceTable.Id_s2_trainstart_time, str_trainstart_time);
                componentProvider.setText(ResourceTable.Id_s2_trainserial, str_trainserial);
                componentProvider.setText(ResourceTable.Id_s2_seatingno, str_seatingno);
                componentProvider.setText(ResourceTable.Id_s2_checkport, str_checkport);
            }
            providerFormInfo.mergeActions(componentProvider);
        }

        return providerFormInfo;
    }

    @Override
    protected void onUpdateForm(long formId) {
        HiLog.info(TAG, "onUpdateForm");
        super.onUpdateForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onUpdateFormData(formId);

    }


    @Override
    protected void onDeleteForm(long formId) {
        HiLog.info(TAG, "onDeleteForm: formId=" + formId);
        super.onDeleteForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onDeleteForm(formId);
        formControllerManager.deleteFormController(formId);
        //移除卡片就移除数据表
        OrmPredicates predicates = connect.where(Form.class);
        predicates.equalTo("formID", formId);
        List<Form> users = connect.query(predicates);
        Form form = users.get(0);
        connect.delete(form);
        connect.flush();
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        HiLog.info(TAG, "onTriggerFormEvent: " + message);
        super.onTriggerFormEvent(formId, message);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onTriggerFormEvent(formId, message);
    }

    private boolean intentFromWidget(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        return formId != INVALID_FORM_ID;
    }

    private String getRoutePageSlice(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        if (formId == INVALID_FORM_ID) {
            return null;
        }
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        if (formController == null) {
            return null;
        }
        Class<? extends AbilitySlice> clazz = formController.getRoutePageSlice(intent);
        if (clazz == null) {
            return null;
        }
        return clazz.getName();
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (intentFromWidget(intent)) { // Only response to it when starting from a service widget.
            String newWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice == null || !topWidgetSlice.equals(newWidgetSlice)) {
                topWidgetSlice = newWidgetSlice;
                restart();
            }
        } else {
            if (topWidgetSlice != null) {
                topWidgetSlice = null;
                restart();
            }
        }
    }
}
